package com.ykq.system.service.impl;

import com.ykq.core.entity.Menu;
import com.ykq.core.util.WebUtil;
import com.ykq.core.vo.R;
import com.ykq.system.mapper.MenuMapper;
import com.ykq.system.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 闫克起
 * @Description:
 * @Date: Create in 11:55 2024/8/12
 */
@Service
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Override
    public R<List<Menu>> selectByUserId(Long userId) {
        List<Menu> menus = menuMapper.queryByUserId(userId);
        if(menus.size()==0){
            return R.error("用户没有权限");

        }
        return R.ok(menus);
    }

    @Override
    public R<List<Menu>> selectLeftMenu() {
        //获取当前用户的名
        String username = WebUtil.getUsername();
        //根据用户名查询菜单
        List<Menu> menus = menuMapper.selectLeftMenu(username);
        //封装菜单
        //1. 得到一级菜单
        List<Menu> firstMenus = menus.stream().filter(menu -> menu.getParentId().equals(0L)).collect(Collectors.toList());

        //2. 得到一级菜单对应的子菜单
        firstMenus.forEach(menu -> {
            //得到一级菜单的id
            Long menuId = menu.getMenuId();
            //根据一级菜单的id查询对应的子菜单
            List<Menu> children = menus.stream().filter(m -> m.getParentId().equals(menuId)).collect(Collectors.toList());
            //设置子菜单
            menu.setChildren(children);
        });


        return R.ok(firstMenus);
    }
}



















